package com.qiuling.iot.rabbit;

import com.google.gson.Gson;
import com.qiuling.iot.entity.EquipmentData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

/**
 * @Author：zhangqiang
 * @Description：
 * @Date：Created in 0:07 2020/3/13
 * @Modified By：
 */
@Component
@Slf4j
public class MyMessageConverter implements MessageConverter {

    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        log.info("=======toMessage=========");
        String jsonStr = null;
        if(o instanceof EquipmentData) {
            Gson gson = new Gson();
            jsonStr = gson.toJson(o);
        }
        return new Message(jsonStr.getBytes(), messageProperties);
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        log.info("=======fromMessage=========");
        String jsonString = new String(message.getBody());
        /**
         * 这里的json字符串不知为何多了首尾双引号，所以要去掉
         * 然后去转义（不去掉转义会报错）
         */
        jsonString = jsonString.substring(1, jsonString.length()-1);
        jsonString = StringEscapeUtils.unescapeJava(jsonString);
        Gson gson = new Gson();
        EquipmentData equipmentData = gson.fromJson(jsonString, EquipmentData.class);
        return equipmentData;
    }
}
